package com.cjj.thread_safe;

class ThreadTrain implements Runnable {

    // 车票总数
    private int count = 100;

    private Object object = new Object();

    @Override
    public void run() {
        while (count > 0) {
            try {
                Thread.sleep(40);
            } catch (Exception e) {

            }
            synchronized (object) {
                if (count > 0) {
                    System.out.println(Thread.currentThread().getName() + "出售第" + (100 - count + 1) + "张票");
                    count--;
                }
            }
        }
    }
}

/**
 * 什么是线程不安全？
 * 当多个线程同时操作同一个 共享的全局变量可能会受到其它线程的干扰，会引发数据冲突
 * 线程不安全问题如何解决？
 * 1.Synchronized
 * 2.jdk1.5并发包，lock锁
 *
 * @ClassName Thread_01
 * @Date 2021/07/17 11:23:43
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class Thread_01 {

    public static void main(String[] args) {
        // 创建两个线程, 线程类一定要是一个实例
        ThreadTrain threadTrain = new ThreadTrain();
        Thread thread_1 = new Thread(threadTrain);
        Thread thread_2 = new Thread(threadTrain);
        thread_1.start();
        thread_2.start();
    }

}
